import Vue from 'vue';

/**
 * 返回绑定v-dramMove指令的元素外层的父元素
*/
function findRootElement(elList) {
	for (let item of elList) {
		if (item.tagName === 'DIV' && item.className === 'layui-layer-iframe') {
			return item;
		}
	}
}

/**
 * 拖动元素指令
*/
Vue.directive('drawMove', {
	// 被拖动元素
	inserted: function (el, binding, vNode) {
		el.setAttribute('style', 'position: fixed; cursor: move;');
	},

	bind: function (el, bindding, vNode) {
		el.setAttribute('draggable', true);
		let left, top;
		el._dragStart = function (event) {
			event.stopPropagation();
			left = event.clientX - el.offsetLeft;
			top = event.clientY - el.offsetTop;
		};

		// 防止被拖出边界
		// el._checkPosition = function () {
		// 	const width = el.offsetWidth;
		// 	const height = el.offsetHeight;
		// 	let left = Math.min(el.offsetLeft, document.body.clientWidth - width);
		// 	left = Math.max(0, left);
		// 	let top = Math.min(el.offsetTop, document.body.clientHeight - height);
		// 	top = Math.max(0, top);
		// 	el.style.left = left + 'px';
		// 	el.style.top = top + 'px';
		// 	el.style.width = width + 'px';
		// 	el.style.height = height + 'px';
		// };

		el._dragEnd = function (event) {
			event.stopPropagation();
			let currentLeft = event.clientX - left;
			let currentTop = event.clientY - top;
			const elementPath = event.path || event.composedPath();
			const dramRootElement = findRootElement(elementPath);
			if (dramRootElement) {
				console.log('dramRootElement', dramRootElement);
				let dramRootElementStyle = dramRootElement.getAttribute('style').toString();
				dramRootElement.setAttribute('style', 'position: fixed;' + dramRootElementStyle);
				dramRootElement.className = dramRootElement.getAttribute('class');
				dramRootElement.style.left = currentLeft + 'px';
				dramRootElement.style.top = currentTop + 'px';
			} else {
				el.style.left = currentLeft + 'px';
				el.style.top = currentTop + 'px';
			}
			// el._checkPosition();
		};

		el._documentAllowDraop = function (event) {
			event.preventDefault();
		};

		document.body.addEventListener('dragover', el._documentAllowDraop);
		el.addEventListener('dragstart', el._dragStart);
		el.addEventListener('dragend', el._dragEnd);
		// window.addEventListener('resize', el._checkPosition);
	},

	unbind: function (el, bindding, vNode) {
		document.body.removeEventListener('dragover', el._documentAllowDraop);
		el.removeEventListener('dragstart', el._dragStart);
		el.removeEventListener('dragend', el._dragEnd);
		// window.removeEventListener('resize', el._checkPosition);
		delete el._documentAllowDraop;
		delete el._dragStart;
		delete el._dragEnd;
		// delete el._checkPosition;
	}
});

